package com.blqy.fr.user.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.blqy.fr.common.constant.RedisConstant;
import com.blqy.fr.common.util.AuthContextHolder;
import com.blqy.fr.model.user.User;
import com.blqy.fr.vo.user.UserVo;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        try {
            String token = getTokenFromHeader(request);
            if (StringUtils.isNotBlank(token)) {
                // 从 Redis 获取用户信息
                UserVo userVo = (UserVo) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
                if (userVo != null) {
//                    UserVo userVo = JSON.parseObject(userJson, UserVo.class);
                    if (userVo != null && userVo.getId() != null) {
                        // 设置当前用户 ID 到 ThreadLocal
                        AuthContextHolder.setUserId(userVo.getId());
                        AuthContextHolder.setUsername(userVo.getNickName());
                        log.debug("Token 验证成功，用户ID: {}", userVo.getId());
                    } else {
                        log.warn("Token 对应的用户信息无效，token: {}", token);
                    }
                } else {
                    log.debug("Token 已过期或无效，token: {}", token);
                }
            }

            // 继续执行后续过滤器和 Controller
            filterChain.doFilter(request, response);

        } catch (Exception e) {
            log.error("TokenAuthenticationFilter 发生异常", e);
            // 可选：返回 401，但通常放行让 Controller 统一处理更合适
            // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            // return;
            filterChain.doFilter(request, response);
        } finally {
            // 清理 ThreadLocal，防止内存泄漏
            AuthContextHolder.removeUserId();
            AuthContextHolder.removeUsername();
        }
    }

    /**
     * 从请求头中提取 Bearer Token
     */
    private String getTokenFromHeader(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(authHeader) && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7).trim();
        }
        return null;
    }
}